package org.tea.inventory.admin.web.product;

import cn.hutool.core.io.resource.ResourceUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.tea.inventory.admin.web.admin.BaseController;
import org.tea.inventory.base.exception.ApplicationException;
import org.tea.inventory.base.response.BaseResponse;
import org.tea.inventory.base.util.ResponseUtil;
import org.tea.inventory.base.util.excel.ExcelView;
import org.tea.inventory.base.util.excel.ExportExcel;
import org.tea.inventory.domain.tea.Product;
import org.tea.inventory.service.IProductService;
import org.tea.inventory.service.impl.IProductExcelService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品属性Controller
 * 
 * @author dongxb
 * @date 2025-04-07
 */
@Api(tags = "商品管理-商品属性控制器")
@Slf4j
@RestController
@RequestMapping("/admin/product")
@RequiredArgsConstructor
public class ProductController extends BaseController {
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductExcelService productExcelService;

    /**
     * 查询商品属性列表
     */
    @GetMapping("page")
    @ApiOperation(value = "获取商品属性列表")
    @ApiResponses(
            @ApiResponse(code = 0, message = "成功", response = Product.class)
    )
    public BaseResponse page(Product product)
    {
        log.info("product=" + product.toString());
        startPage();
        List<Product> list = productService.selectProductList(product);
        return getDataTable(list);
    }

    @GetMapping("/export")
    @ApiOperation(value = "导出商品属性列表")
    public void exportProduct(Product product, HttpServletRequest request, HttpServletResponse response) {
        log.info("product=" + product.toString());
        Map<String, Object> map = new HashMap<>();
        String title = "商品属性列表";
        String header = "商品编号,商品名称,商品简称,商品类别,商品品牌,商品状态,单价,销售价,成本,重量,商品级别,商品系列,打包方式,产地,采摘季节,保质期,陈化年份,存储要求,创建时间";
        String column = "productCode,productName,productShortForm,categoryName,brandName,statusStr,price,salePrice,costPrice,weight,teaLevel,teaSeries,teaPackageFormat,teaOrigin,teaGetSeason,teaSellbyDate,teaAgingYear,teaStorageRequire,createDateStr";
        map.put("biaoti", title);
        map.put("header", header);
        map.put("column", column);
        try {
            List<Product> productCategories = productService.selectProductList(product);
            List<Map> list = JSONArray.parseArray(JSON.toJSONString(productCategories), Map.class);
            ExportExcel.export(request, response, list, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取商品属性详细信息
     */
    @GetMapping("/read")
    @ApiOperation(value = "获取商品属性详细信息")
    public Object read(Long id){
        if(id == null){
            return ResponseUtil.badArgument();
        }

        Product product = productService.selectProductById(id);
        return ResponseUtil.ok(product);
    }

    /**
     * 新增商品属性
     */
    @PostMapping(value = "/add")
    @ApiOperation(value = "新增商品属性")
    public BaseResponse add(@Validated @RequestBody Product product)
    {
        log.info("product=" + product.toString());

        if (!productService.checkProductCodeUnique(product)) {
            log.error("类别编号唯一校验失败");
            throw  new ApplicationException(-1,"新增商品失败，商品编号" + product.getProductCode() + "已存在");
        }

        return ResponseUtil.ok(productService.insertProduct(product));
    }

    /**
     * 修改商品属性
     */
    @PostMapping(value = "/edit")
    @ApiOperation(value = "修改商品属性")
    public BaseResponse edit(@Validated @RequestBody Product product)
    {
        log.info("product=" + product.toString());
        return ResponseUtil.ok(productService.updateProduct(product));
    }

    /**
     * 删除商品属性
     */
    @PostMapping(value = "/remove")
    @ApiOperation(value = "删除商品属性")
    public BaseResponse remove(Long id)
    {
        return ResponseUtil.ok(productService.deleteProductByCode(id));
    }

}
